#include <iostream>
using namespace std;
#include <hidl/HidlTransportSupport.h>
#include <utils/Looper.h>
#include <utils/StrongPointer.h>
#include <log/log.h>
#include "Server.h"
#include "BufManager.h"
#include "FreetypeWrapper.h"
#include "wmark_dev.h"
using android::FreetypeWrapper;
using android::hardware::configureRpcThreadpool;
using android::hardware::joinRpcThreadpool;

using android::wmark::BufManager;
using android::wmark::Server;
using vendor::mega::hardware::common::mega_camera_enhancement::server::V1_0::IWmarkServer;

void read_buffer(void *buffer, unsigned long len)
{
	int i;
	unsigned char *ptr = (unsigned char *)buffer;
    int cout = 0;

	if (!ptr) {
		fprintf(stderr, "<%s>: Invalid buffer...\n", __func__);
		return;
	}

	printf("Read buffer content:\n");
	for (i = 0; i < len; i++) {
        if (ptr[i] != 0) {
            cout++;
        }
    }

	printf("!=0 cout=%d\n", cout);
}

void testBufsInitInterface()
{
    wmark_buf_t msg;
    BufManager *bufManager = new BufManager();
    FreetypeWrapper *freetype = new FreetypeWrapper();
    
    int testX = 0, testY = 0;
    int wmarkBufId = 0;

    while (1)
    {
        uint8_t strBuf[60 * 700] = {0};
        uint64_t endLen = 0;
        std::string txt = "你好,world_" + std::to_string(wmarkBufId);
        if (wmarkBufId >= 12) {
            wmarkBufId = 0;
        }

        
        freetype->text2img(txt, strBuf, 60 , 700, endLen);

        if (testX >= 1028) {
            testX = 0;
        }

        if (testY >= 960) {
            testY = 0;
        }

        msg.info.wmark_buf_id = wmarkBufId;
        msg.info.picture.type = TYPE_STR;
        msg.info.picture.display.ch = 1;
        msg.info.picture.display.en = 1;
        msg.info.picture.display.face_id.id1 = 4;
        msg.info.picture.display.w = 700;
        msg.info.picture.display.h = 60;
        msg.info.picture.display.len = 700 * 60;
        msg.info.picture.display.x = testX + wmarkBufId * 30;
        msg.info.picture.display.y = testY + wmarkBufId * 60;

        msg.info.picture.display.bg.r = 47;
        msg.info.picture.display.bg.g = 49;
        msg.info.picture.display.bg.b = 51;
        
        read_buffer(strBuf, endLen);
        bufManager->sendNotify(strBuf, endLen, msg);
        testY++;
        testX++;

        wmarkBufId++;
        // break;
    }
}

int main(int argc, char **argv)
{
    // sleep for a second, wait /data/vendor to be mounted
    sleep(1);

    configureRpcThreadpool(4, true /* callerWillJoin */);

    android::sp<IWmarkServer> service = new Server();
    android::status_t ret = service->registerAsService();

    if (ret != android::NO_ERROR)
    {
        ALOGE("%s %d register server fail", __func__, __LINE__);
    }

    // testBufsInitInterface();

    joinRpcThreadpool();
    return 0;
}
